<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>

        class SuperTask {
            constructor(count = 2) {
                this.count = count
            }
            runQueue = []
            running = 0
            add(task) {
                return new Promise((resolve, reject) => {
                    if (this.running < this.count) {
                        this.runTask(task, resolve, reject)
                    } else {
                        this.runQueue.push({ task, res: resolve, rej: reject })
                    }
                })
            }

            runTask(task, res, rej) {
                this.running++
                task().then(() => {
                    res()
                }).catch(() => {
                    rej()
                }).finally(() => {
                    this.running--
                    if (this.runQueue.length) {
                        const { task, res, rej } = this.runQueue.shift()
                        this.runTask(task, res, rej)
                    }
                })
            }
        }

        function timeout(time) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    resolve()
                }, time)
            })
        }

        const superTask = new SuperTask(2)

        function addTask(time, name) {
            superTask.add(
                () => timeout(time)
            ).then(() => {
                console.log(`任务${name}完成`);
            })
        }

        addTask(10000, '1')
        addTask(5000, '2')
        addTask(3000, '3')
        addTask(4000, '4')
        addTask(5000, '5')




    </script>
</body>

</html>